import { Builder, By, until, Key } from 'selenium-webdriver'
// import chrome from 'selenium-webdriver/chrome'
import firefox from 'selenium-webdriver/firefox'

// var driver = new Builder()
//     .forBrowser('chrome')
//     // .setChromeOptions(new chrome.Options().headless())
//     .build();
// var driver = new Builder()
//     .forBrowser('MicrosoftEdge')
//     .build();
var driver = new Builder()
    .forBrowser('firefox')
    .setFirefoxService(new firefox.ServiceBuilder("./geckodriver.exe"))
    // .setFirefoxOptions(new firefox.Options().headless())
    .build();

// let mdPath = 'C:\\Users\\duan\\Documents\\WPS Cloud Files\\279367518\\UDP与IP分片.md'
let url = 'https://csdn.net/'
let mdUrl = 'https://editor.csdn.net/md?not_checkout=1'
let domain = '.csdn.net'
let httpOnlyCookies = [ 'UserInfo', 'UserToken', 'SESSION']
// let secureCookies: Array<string> = []
// 
let contentXPath = '/html/body/div[1]/div[1]/div[2]/div/div[2]/div[1]/div[2]/pre'
let titleXpath = '/html/body/div[1]/div[1]/div[1]/div/div[2]/input'
let publishButtonXPath = '/html/body/div[1]/div[1]/div[1]/div/div[3]/button[2]'
// let publishModalXPath = '/html/body/div[1]/div[2]'
let publishModalClassPath = 'html body div.app.app--light div.modal'
let addTagButtonXpath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[3]/div/div/div[1]/button'
let inputTagXPath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[3]/div/div/div[2]/div[2]/div/div[1]/input'
let closeTagDialogXPath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[3]/div/div/div[2]/div[4]/button'
// let tagListXPath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[3]/div/div/div/span[1]/span'
// let typeXpath = '//*[@id="tagList"]/button'
let typeListXpath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[4]/div/div/div[2]/div[2]/div'
let originalXpath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[5]/div/div/label[1]'
let classXPath = '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[9]/div/div/label[1]'
let publishSubmitXpath = '/html/body/div[1]/div[2]/div/div[1]/div[2]/button[4]'
let blogUrlXpath = '/html/body/div[2]/div/div/div/div[2]/section/div/div[1]/div/section/section/main/div/div/div/div/div/div/div[2]/a[1]'

/**
 * cookies 发布文章
 * @param {String} cookies 
 */
async function CSDNAutoDeployBlog(cookies: string, blogContent: blogContent) {

    driver.get(url)
    // 使用Cookies进行登录
    await cookiesLogin(cookies)
    // =====================================
    // 进入写博客页面
    await driver.sleep(2000)
    await driver.get(mdUrl)
    await driver.wait(until.elementLocated(By.xpath(contentXPath)))
    driver.findElement(By.xpath(contentXPath)).sendKeys(Key.CONTROL, 'a', Key.DELETE)
    driver.findElement(By.xpath(titleXpath)).sendKeys(Key.CONTROL, 'a', Key.DELETE)
    // 填入博客标题，内容
    let { mdContent, titleObj } = blogContent
    await driver.findElement(By.xpath(contentXPath)).sendKeys(mdContent.join('\n'))
    await driver.findElement(By.xpath(titleXpath)).sendKeys(titleObj.title)
    // 进入发布流程
    await driver.sleep(2000)
    await driver.findElement(By.xpath(publishButtonXPath)).click()
    try {
        await driver.wait(until.elementLocated(By.css(publishModalClassPath)), 3000)
    } catch(error) {
        console.log('error :>> ', error);
        driver.findElement(By.xpath(publishButtonXPath)).click()
    }
    
    // 输入标签信息
    await driver.sleep(1000) // 等待标签接口返回    
    await driver.findElement(By.xpath(addTagButtonXpath)).click()
    let tagArr = titleObj.tags.split(',')
    console.log('tagArr :>> ', tagArr);
    for (let i = 0; i < tagArr.length; i++) {
        const tag = tagArr[i];
        await driver.findElement(By.xpath(inputTagXPath)).sendKeys(Key.CONTROL, 'a', Key.DELETE)
        await driver.findElement(By.xpath(inputTagXPath)).sendKeys(tag)
        await driver.sleep(500)
        await driver.findElement(By.xpath(inputTagXPath)).sendKeys(Key.ENTER)
    }
    
    await driver.findElement(By.xpath(closeTagDialogXPath)).click()


    // let tagNameList = []
    // for (let i = 0; i < tagListEle.length; i ++) {
    //     let tag = await tagListEle[i].getText()
    //     tagNameList.push(tag)
    // }
    // console.log('tagNameList :>> ', tagNameList);
    // if (tagListEle.length == 0) {
    //     // TODO 手动添加标签
    //     // await driver.findElement(By.xpath(tagXpath)).click()
    // }
    // 输入专栏信息
    let typeListEle = await driver.findElements(By.xpath(typeListXpath))
    let typeNameList = []
    for (let i = 0; i < typeListEle.length; i ++) {
        let inputEle = await typeListEle[i].findElement(By.css('input'))
        let typeName = await inputEle.getAttribute('value')
        typeNameList.push(typeName)
        if (typeName.trim().toLowerCase() == 'javascript') {
            typeListEle[i].click()
        }
    }
    console.log('typeNameList :>> ', typeNameList);
    // 输入文章类型
    await driver.findElement(By.xpath(originalXpath)).click()
    // 输入文章等级
    await driver.findElement(By.xpath(classXPath)).click()
    
    // 发布文章
    await driver.findElement(By.xpath(publishSubmitXpath)).click()
    let blogUrlEle = await driver.wait(until.elementLocated(By.xpath(blogUrlXpath)))
    let blogUrl = await blogUrlEle.getAttribute('href')
    console.log('blogUrl :>> ', blogUrl);
    console.log('END!!!')
    return blogUrl;
}

async function cookiesLogin(cookies: string) {

    await driver.manage().deleteAllCookies()
    
    let array = cookies.split(';').map(_ => _.trim());
    array.forEach(async item => {
        
        let index = item.indexOf('=')

        let keyValue = [
            item.substring(0, index),
            item.substring(index + 1)
        ]

        console.log('keyValue :>> ', keyValue);
        if (keyValue[1]) {
            await driver.manage().addCookie({
                name: keyValue[0],
                value: keyValue[1],
                domain: domain,
                httpOnly: !!httpOnlyCookies.find(_ => _ == keyValue[0]),
                // secure: !!secureCookies.find(_ => _ == item),
            });
        }
    });

    // 查看所有 Cookies
    // driver.manage().getCookies().then(function (cookies) {
    //     console.log('cookie details => ', cookies);
    // });
}

export {
    CSDNAutoDeployBlog
} 
